(function($) {
	// Search
	var $searchWrap = $('.search-form-wrap'),
		isSearchAnim = false,
		searchAnimDuration = 200;

	var startSearchAnim = function() {
		isSearchAnim = true;
	};

	var stopSearchAnim = function(callback) {
		setTimeout(function() {
			isSearchAnim = false;
			callback && callback();
		}, searchAnimDuration);
	};

	$('.nav-item-search').on('click', function() {
		if (isSearchAnim) return;
		startSearchAnim();
		$searchWrap.addClass('on');
		stopSearchAnim(function() {
			$('.local-search-input').focus();
		});
	});

	$(document).mouseup(function(e) {
		var _con = $('.local-search');
		if (!_con.is(e.target) && _con.has(e.target).length === 0) {
			$searchWrap.removeClass('on');
		}
	});

	// 移动设备侦测
	var isMobile = {
		Android: function() {
			return navigator.userAgent.match(/Android/i);
		},
		BlackBerry: function() {
			return navigator.userAgent.match(/BlackBerry/i);
		},
		iOS: function() {
			return navigator.userAgent.match(/iPhone|iPad|iPod/i);
		},
		Opera: function() {
			return navigator.userAgent.match(/Opera Mini/i);
		},
		Windows: function() {
			return navigator.userAgent.match(/IEMobile/i);
		},
		any: function() {
			return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
		}
	};

	// 建议在移动端不初始化，其实 /search.xml 文件还挺大的，
	if ($('.local-search').size()) {
		$.getScript('/js/search.js', function() {
			searchFunc("/search.xml", 'local-search-input', 'local-search-result');
		});
	}

	// Share
	$('.share-outer').click(() => $('.share-wrap').fadeToggle())

	// lazyload
	$("img.lazy").lazyload({
		effect: "fadeIn"
	});

	// justifiedGallery
	$('#gallery').justifiedGallery({
		rowHeight: 200,
		margins: 5
	});

	// scroll down
	$(document).ready(function($) {
		$('.anchor').click(function(e) {
			e.preventDefault();
			$('main').animate({
				scrollTop: $('.cover').height()
			}, 'smooth');
		});
	});

	// To top
	(function($) {
		// When to show the scroll link
		// higher number = scroll link appears further down the page
		var upperLimit = 1000;

		// Our scroll link element
		var scrollElem = $('#totop');

		// Scroll to top speed
		var scrollSpeed = 1600;

		// Show and hide the scroll to top link based on scroll position
		scrollElem.hide();
		$('.content').scroll(function() {
			var scrollTop = $('.content').scrollTop();
			if (scrollTop > upperLimit) {
				$(scrollElem).stop().fadeTo(300, 1); // fade back in
			} else {
				$(scrollElem).stop().fadeTo(300, 0); // fade out
			}
		});

		// Scroll to top animation on click
		$(scrollElem).click(function() {
			$('.content').animate({
				scrollTop: 0
			}, scrollSpeed);
			return false;
		});
	})(jQuery);

	// Mobile nav
	var $content = $('.content'),
		$sidebar = $('.sidebar');

	$('.navbar-toggle').on('click', function() {
		$content.toggleClass('on');
		$sidebar.toggleClass('on');
	});

	$($content).on('click', function() {
		$content.removeClass('on');
		$sidebar.removeClass('on');
	});

	if (window.matchMedia("(min-width: 768px)").matches) {
		$content.addClass('on');
		$sidebar.addClass('on');
	}

	// reward
	$('#reward-btn').on('click', function() {
		$('#reward').fadeIn(150)
		$('#mask').fadeIn(150)
	});
	$('#reward .close, #mask').on('click', function() {
		$('#mask').fadeOut(100)
		$('#reward').fadeOut(100)
	})

	function getUrlVars(url) {
		if(!url) return "";
		var hash;
		var myJson = {};
		var hashes = url.slice(url.indexOf('?') + 1).split('&');
		for (var i = 0; i < hashes.length; i++) {
			hash = hashes[i].split('=');
			myJson[hash[0]] = hash[1];
		}
		return myJson;
	}
	var Obsidian = {
		setCodeRowWithLang: function() {
			var code = $("code");
			if (code && code.length) {
				code.each(function() {
					var item = $(this),
						lang = "",
						codeOption = "",
						$className = item[0].className;
					codeOption = getUrlVars($className.split("?")[1]);
					$className = $className.split("?")[0];
					if ($className.indexOf(' ') > -1) {
						lang = $className.split(' ')[0];
					} else if ($className.indexOf('.') > -1) {
						lang = $className.split(".")[1];
					} else {
						lang = $className;
					}
					var langMap = {
						"html": "HTML",
						"xml": "XML",
						"svg": "SVG",
						"mathml": "MathML",
						"css": "CSS",
						"clike": "C-like",
						"js": "JavaScript",
						"abap": "ABAP",
						"apacheconf": "Apache Configuration",
						"apl": "APL",
						"arff": "ARFF",
						"asciidoc": "AsciiDoc",
						"adoc": "AsciiDoc",
						"asm6502": "6502 Assembly",
						"aspnet": "ASP.NET (C#)",
						"autohotkey": "AutoHotkey",
						"autoit": "AutoIt",
						"shell": "BASH",
						"bash": "BASH",
						"basic": "BASIC",
						"csharp": "C#",
						"dotnet": "C#",
						"cpp": "C++",
						"cil": "CIL",
						"csp": "Content-Security-Policy",
						"css-extras": "CSS Extras",
						"django": "Django/Jinja2",
						"jinja2": "Django/Jinja2",
						"dockerfile": "Docker",
						"erb": "ERB",
						"fsharp": "F#",
						"gcode": "G-code",
						"gedcom": "GEDCOM",
						"glsl": "GLSL",
						"gml": "GameMaker Language",
						"gamemakerlanguage": "GameMaker Language",
						"graphql": "GraphQL",
						"hcl": "HCL",
						"http": "HTTP",
						"hpkp": "HTTP Public-Key-Pins",
						"hsts": "HTTP Strict-Transport-Security",
						"ichigojam": "IchigoJam",
						"inform7": "Inform 7",
						"javastacktrace": "Java stack trace",
						"json": "JSON",
						"jsonp": "JSONP",
						"latex": "LaTeX",
						"emacs": "Lisp",
						"elisp": "Lisp",
						"emacs-lisp": "Lisp",
						"lolcode": "LOLCODE",
						"markup-templating": "Markup templating",
						"matlab": "MATLAB",
						"mel": "MEL",
						"n1ql": "N1QL",
						"n4js": "N4JS",
						"n4jsd": "N4JS",
						"nand2tetris-hdl": "Nand To Tetris HDL",
						"nasm": "NASM",
						"nginx": "nginx",
						"nsis": "NSIS",
						"objectivec": "Objective-C",
						"ocaml": "OCaml",
						"opencl": "OpenCL",
						"parigp": "PARI/GP",
						"objectpascal": "Object Pascal",
						"php": "PHP",
						"php-extras": "PHP Extras",
						"plsql": "PL/SQL",
						"powershell": "PowerShell",
						"properties": ".properties",
						"protobuf": "Protocol Buffers",
						"q": "Q (kdb+ database)",
						"jsx": "React JSX",
						"tsx": "React TSX",
						"renpy": "Ren'py",
						"rest": "reST (reStructuredText)",
						"sas": "SAS",
						"sass": "SASS (Sass)",
						"scss": "SASS (Scss)",
						"sql": "SQL",
						"soy": "Soy (Closure Template)",
						"tap": "TAP",
						"toml": "TOML",
						"tt2": "Template Toolkit 2",
						"ts": "TypeScript",
						"vbnet": "VB.Net",
						"vhdl": "VHDL",
						"vim": "vim",
						"visual-basic": "Visual Basic",
						"vb": "Visual Basic",
						"wasm": "WebAssembly",
						"wiki": "Wiki markup",
						"xeoracube": "XeoraCube",
						"xojo": "Xojo (REALbasic)",
						"xquery": "XQuery",
						"yaml": "YAML"
					};

					var displayLangText = "";
					if ($className.indexOf('.') > -1) {
						displayLangText = $className
					} else {
						if (lang in langMap) displayLangText = langMap[lang];
						else displayLangText = lang;
					}
					//显示的标题添加备注
					displayLangText +=(codeOption.note?" <span>[ "+codeOption.note+" ]</span> ":"");
					if (item.find(".language-mark").length <= 0 && displayLangText) {
						item.css('background', 'transparent');
						item.css('padding', 0);

						var $code = item.text();
						item.empty();
						var myCodeMirror = CodeMirror(this, {
							value: $code,
							mode: Obsidian.getCodeMirrorMode(lang),
							lineNumbers: !item.is('.inline'),
							readOnly: true,
							lineWrapping: true,
							theme: 'dracula',
							scrollbarStyle: null
						});

						item.find('.CodeMirror').prepend(
							'<span class="language-mark" ref=' + lang + '> ' + displayLangText + '</span>');

						if (codeOption.hide == 1) {
							item.children(".CodeMirror").children(".CodeMirror-scroll").hide();
							item.find('.CodeMirror').prepend(
								'<span class="collapse-code">+</span>');
							item.find('.language-mark').after(
								'<span class="collapse-code-lines">' + myCodeMirror.lineCount() + ' lines</span>');
						} else {
							item.find('.CodeMirror').prepend(
								'<span class="collapse-code">-</span>');
							item.find('.language-mark').after(
								'<span class="collapse-code-lines hide">' + myCodeMirror.lineCount() + ' lines</span>');
						}
					}
				});
			}
		},
		v: function(t, e) {
			if (t) switch (t) {
				case "javascript":
				case "text/javascript":
				case "js":
					return t = "javascript";
				case "json":
					return e ? t : t = {
						name: "javascript",
						json: !0
					};
				case "jsonld":
				case "json-ld":
					return e ? t : "application/ld+json";
				case "text/typescript":
				case "typescript":
				case "ts":
					return e ? "typescript" : t = {
						name: "javascript",
						typescript: !0
					};
				case "clojure":
					return t;
				case "coffee":
				case "coffeescript":
				case "css":
					return t;
				case "less":
					return e ? "less" : "text/x-less";
				case "scss":
					return e ? "scss" : t = "text/x-scss";
				case "gfm":
				case "github flavored markdown":
					return t = "gfm";
				case "markdown":
				case "md":
				case "mkd":
					return t;
				case "xml":
				case "xaml":
				case "mjml":
				case "xul":
				case "enml":
					return e ? t : "xml";
				case "haskell":
					return t;
				case "htmlmixed":
				case "html":
				case "xhtml":
				case "svg":
				case "epub":
					return e ? /^html/.exec(t) ? "html" : t : t = "htmlmixed";
				case "lua":
					return t;
				case "lisp":
				case "commonlisp":
				case "common lisp":
					return t = "commonlisp";
				case "pascal":
					return t;
				case "perl":
				case "perl5":
				case "perl4":
				case "perl3":
				case "perl2":
					return "perl";
				case "perl6":
					return t;
				case "php+html":
					return e ? "php" : "application/x-httpd-php";
				case "php":
				case "php3":
				case "php4":
				case "php5":
				case "php6":
					return e ? t : "text/x-php";
				case "cython":
					return e ? t : t = "text/x-cython";
				case "python":
					return e ? t : t = "text/x-python";
				case "ruby":
					return t;
				case "shell":
				case "sh":
				case "zsh":
				case "bash":
					return t = "shell";
				case "sql":
				case "sql lite":
				case "sqlite":
					return e ? t : t = "text/x-sql";
				case "mssql":
					return e ? t : t = "text/x-mssql";
				case "mysql":
					return e ? t : t = "text/x-mysql";
				case "mariadb":
					return e ? t : t = "text/x-mariadb";
				case "cassandra":
				case "cql":
					return e ? t : t = "text/x-cassandra";
				case "plsql":
					return e ? t : t = "text/x-plsql";
				case "stex":
				case "tex":
				case "latex":
					return e ? t : "text/x-stex";
				case "tiddlywiki":
				case "wiki":
					return e ? t : t = "tiddlywiki";
				case "vb":
				case "visual basic":
				case "visualbasic":
				case "basic":
					return e ? t : t = "vb";
				case "vbscript":
				case "velocity":
					return t;
				case "verilog":
					return e ? t : t = "text/x-verilog";
				case "xquery":
					return t;
				case "yaml":
				case "yml":
					return e ? t : "yaml";
				case "go":
				case "groovy":
				case "nginx":
					return t;
				case "octave":
				case "matlab":
					return e ? t : "text/x-octave";
				case "c":
				case "clike":
				case "csrc":
					return e ? t : t = "text/x-csrc";
				case "c++":
				case "c++src":
				case "cpp":
				case "cc":
				case "hpp":
				case "h++":
				case "h":
					return e ? t : t = "text/x-c++src";
				case "obj-c":
				case "objc":
				case "objective c":
				case "objective-c":
				case "objectivec":
					return e ? t : t = "text/x-objectivec";
				case "text/x-scala":
				case "scala":
					return e ? t : t = "text/x-scala";
				case "csharp":
				case "c#":
				case "cs":
					return e ? t : t = "text/x-csharp";
				case "java":
					return e ? t : t = "text/x-java";
				case "squirrel":
					return e ? t : t = "text/x-squirrel";
				case "ceylon":
					return e ? t : t = "text/x-ceylon";
				case "kotlin":
					return e ? t : t = "text/x-kotlin";
				case "swift":
					return t = "swift";
				case "r":
				case "rlang":
				case "r-lang":
					return e ? t : t = "text/x-rsrc";
				case "d":
				case "diff":
				case "erlang":
				case "http":
				case "jade":
					return t;
				case "rst":
				case "restructuredtext":
					return t = "rst";
				case "rust":
				case "jinja2":
					return t;
				case "aspx":
				case "asp":
				case "asp.net":
					return e ? t : t = "application/x-aspx";
				case "jsp":
					return e ? t : t = "application/x-jsp";
				case "erb":
					return e ? t : t = "application/x-erb";
				case "ejs":
				case "embeddedjs":
				case "embedded javaScript":
					return e ? t : t = "application/x-ejs";
				case "powershell":
				case "bat":
				case "cmd":
					return e ? t : "application/x-powershell";
				case "dockerfile":
					return e ? t : "text/x-dockerfile";
				case "jsx":
				case "react":
					return e ? t : "text/jsx";
				case "tsx":
					return e ? t : "text/typescript-jsx";
				case "vue.js":
				case "vue":
				case "vue-template":
					return e ? t : "script/x-vue";
				case "nsis":
					return e ? t : "text/x-nsis";
				case "mathematica":
					return e ? t : "text/x-mathematica";
				case "tiki":
				case "tiki wiki":
				case "tiki-wiki":
				case "tikiwiki":
					return "tiki";
				case "properties":
				case "ini":
					return e ? t : "text/x-properties";
				case "livescript":
					return e ? t : "text/x-livescript";
				case "asm":
				case "assembly":
				case "nasm":
				case "gas":
					return e ? t : "assembly";
				case "toml":
					return e ? t : "text/x-toml";
				case "sequence":
					return "sequence";
				case "flow":
				case "flowchart":
					return "flow";
				case "mermaid":
					return "mermaid";
				case "ocaml":
					return e ? t : "text/x-ocaml";
				case "f#":
				case "fsharp":
					return e ? t : "text/x-fsharp";
				case "elm":
					return e ? t : "text/x-elm";
				case "pgp":
				case "pgp-keys":
				case "pgp-key":
				case "pgp-signature":
				case "asciiarmor":
				case "ascii-armor":
				case "ascii armor":
					return e ? t : "application/pgp";
				case "spreadsheet":
				case "excel":
					return e ? t : "text/x-spreadsheet";
				case "elixir":
					return "elixir";
				case "cmake":
					return e ? t : "text/x-cmake";
				case "cypher":
				case "cypher-query":
					return e ? t : "application/x-cypher-query";
				case "dart":
					return "dart";
				case "django":
					return e ? t : "text/x-django";
				case "dtd":
				case "xml-dtd":
				case "xml dtd":
				case "xmldtd":
					return e ? t : "application/xml-dtd";
				case "dylan":
					return e ? t : "text/x-dylan";
				case "handlebars":
					return e ? t : "text/x-handlebars-template";
				case "idl":
					return e ? t : "text/x-idl";
				case "webidl":
				case "web-idl":
				case "web idl":
					return e ? t : "text/x-webidl";
				case "yacas":
					return e ? t : "text/x-yacas";
				case "mbox":
					return e ? t : "application/mbox";
				case "vhdl":
					return e ? t : "text/x-vhdl";
				case "julia":
					return "julia";
				case "haxe":
					return e ? t : "text/x-haxe";
				case "hxml":
					return e ? t : "text/x-hxml";
				case "fortran":
					return e ? t : "text/x-fortran";
				case "protobuf":
					return e ? t : "text/x-protobuf";
				case "makefile":
					return e ? t : "text/x-makefile";
				case "tcl":
					return e ? t : "text/x-tcl";
				case "scheme":
					return e ? t : "text/x-scheme";
				case "twig":
					return e ? t : "text/x-twig";
				case "sas":
					return e ? t : "text/x-sas";
				case "pseudocode":
					return e ? t : "text/x-pseudocode";
				case "julia":
				case "text/x-julia":
				case "stylus":
				case "cobol":
				case "oz":
				case "sparql":
				case "crystal":
					return t;
				case "asn.1":
					return e ? "ASN.1" : t = "text/x-ttcn-asn";
				case "gherkin":
				case "smalltalk":
				case "turtle":
					return t;
				default:
					return "";
			}
		},
		getCodeMirrorMode: function(t, e, n) {
			var i = ((t = (t = t ? t.toLowerCase() : "").replace(/^\s*\.*lang(uage)*-/g, "").replace(/[{}]/g, "").trim())
					.split(
						/\s+/) || [t])[0],
				r = Obsidian.v(t, n);
			return r || t == i || (r = Obsidian.v(i.replace(/(^[.])|(,$)/g, ""), n)), r || (n ? i : e ? null : t);
		},
	};
	Obsidian.setCodeRowWithLang();

	$(".collapse-code").click(function() {
		//let $div = $(this).parent().children(".CodeMirror-scroll")
		let $div = $(this).siblings(".CodeMirror-scroll");
		let $line = $(this).siblings(".collapse-code-lines")
		$div.toggle();
		$line.toggle();
		if ($div.is(':hidden')) {
			$(this).text('+');
		} else {
			$(this).text('-');
		}
	});
})(jQuery);
